package logic

import (
	"encoding/json"
	"log"
	"mssgserver/constant"
	"mssgserver/db"
	"mssgserver/server/common"
	"mssgserver/server/game/gameConfig"
	"mssgserver/server/game/gameConfig/general"
	"mssgserver/server/game/model"
	"mssgserver/server/game/model/data"
	"time"
)

const (
	GeneralNormal      = 0 //正常
	GeneralComposeStar = 1 //星级合成
	GeneralConvert     = 2 //转换
)

var GeneralService = &generalService{}

type generalService struct {
}

/*
*
查询角色属性
获取武将的信息
*/
func (g *generalService) GetGenerals(rid int) ([]model.General, error) {
	generals := make([]data.General, 0)
	general := &data.General{}
	err := db.Engine.Table(general).Where("rid=?", rid).Find(&generals)
	if err != nil {
		log.Println("GetGenerals查询数据库失败")
		return make([]model.General, 0), common.New(constant.DBError, "GetGenerals查询数据库失败")
	}
	gs := make([]model.General, 0)
	for _, g := range generals {
		gs = append(gs, g.ToModel().(model.General))
	}
	return gs, nil
}

func (g *generalService) NewGeneral(cfgId int, rid int, level int8) (*data.General, error) {
	cfg := general.General.GMap[cfgId]
	//初始 武将 无技能 但是有三个技能槽
	sa := make([]*model.GSkill, 3)
	ss, _ := json.Marshal(sa)
	gen := &data.General{
		PhysicalPower: gameConfig.Base.General.PhysicalPowerLimit,
		RId:           rid,
		CfgId:         cfg.CfgId,
		Order:         0,
		CityId:        0,
		Level:         level,
		CreatedAt:     time.Now(),
		CurArms:       cfg.Arms[0],
		HasPrPoint:    0,
		UsePrPoint:    0,
		AttackDis:     0,
		ForceAdded:    0,
		StrategyAdded: 0,
		DefenseAdded:  0,
		SpeedAdded:    0,
		DestroyAdded:  0,
		Star:          cfg.Star,
		StarLv:        0,
		ParentId:      0,
		SkillsArray:   sa,
		Skills:        string(ss),
		State:         GeneralNormal,
	}

	_, err := db.Engine.Table(gen).Insert(gen)
	if err != nil {
		log.Println("GetGenerals插入", err)
		return nil, err
	}
	return gen, nil
}

/*
*
初始化获取武将的列表
*/
func (g *generalService) MyGenerals(rid int) ([]model.General, error) {
	generalRes := make([]model.General, 0)
	gg := &data.General{}
	gs := make([]*data.General, 0)
	err := db.Engine.Table(gg).Where("rid=?", rid).Find(&gs)
	if err != nil {
		log.Println("武将查询数据库失败")
		return make([]model.General, 0), common.New(constant.DBError, "武将查询数据库失败")
	}
	if len(gs) <= 0 {
		var count = 0
		for {
			if count >= 3 {
				break
			}
			cfgId := general.General.Rand()
			if cfgId != 0 {
				newGeneral, err := g.NewGeneral(cfgId, rid, 0)
				if err != nil {
					log.Println("生成武将失败")
					continue
				}
				gs = append(gs, newGeneral)
				count++
			}
		}
		for _, d := range gs {
			generalRes = append(generalRes, d.ToModel().(model.General))
		}
	}
	return generalRes, nil
}
